package itsm.isperp.module.service.configuration;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.service.TreeNodeService;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.configuration.ConfCategory;
import itsm.isperp.module.entity.configuration.ConfCategoryProperty;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.repository.configuration.ConfCategoryMapper;
import itsm.isperp.module.utils.DbQueryUtils;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 配置分类服务
 * 
 * @author lizx
 * @date 2013-4-29
 */
@Service
public class ConfCategoryService extends TreeNodeService<ConfCategory> {

	@Autowired
	ConfCategoryMapper confCategoryMapper;

	@Autowired
	ConfCategoryPropertyService confCategoryPropertyService;

	@Override
	public ConfCategoryMapper getRepository() {
		return confCategoryMapper;
	}

	/**
	 * 查询指定分类的属性（针对当前分类）
	 * 
	 * @return
	 */
	public List<ConfCategoryProperty> findProperty(String categoryId) {
		return confCategoryPropertyService.findProperty(categoryId);
	}

	/**
	 * 查询分类所包含的属性（所有直接父级属性应该包含）
	 * 
	 * @return
	 */
	public List<Map<String, Object>> findAllProperty(String categoryId) {
		return confCategoryPropertyService.findAllProperty(categoryId);
	}

	/**
	 * 删除实体及其自定义属性
	 */
	@Override
	public ResultMessage delete(String id) {

		ConfCategory cc = this.confCategoryMapper.findOne(id);
		if (cc == null) {
			return ResultMessage.failure();
		}

		boolean b = DbQueryUtils.exists(ConfCi.class, "conf_category_id", id);

		if (b) {
			return ResultMessage.failure("该资产分类包含资产，不能删除！");
		}

		confCategoryPropertyService.deleteCategoryPropertyByCategoryPath(cc
				.getTreenodePath());
		return super.delete(id);

	}
	
	 public String getCategoryIdByName(String name) {
	    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
	    String sql="select id from conf_category where name='"+name+"'";
	    String result=jdbcTemplate.queryForObject(sql, String.class);
	    return result;
	  }

}
